package org.budo.warehouse.web.controller;

import java.io.File;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.budo.support.lang.util.FileUtil;
import org.budo.support.lang.util.IoUtil;
import org.budo.support.servlet.util.ResponseUtil;
import org.budo.support.spring.io.util.ResourceUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author lmw
 */
@Controller
public class AdminController {
    @ResponseBody
    @RequestMapping("admin")
    public void admin(HttpServletResponse response) {
        File file = new File("../budo-warehouse-vue/dist/index.html");
        if (file.exists()) {
            IoUtil.write(IoUtil.fileInputStream(file), ResponseUtil.getOutputStream(response));
            return;
        }

        InputStream inputStream = ResourceUtil.classPathResourceInputStream("index.html");
        if (null != inputStream) {
            IoUtil.write(inputStream, ResponseUtil.getOutputStream(response));
            return;
        }

        String canonicalPath = FileUtil.getCanonicalPath(file);
        ResponseUtil.writeToResponse(response, "#30 文件 " + canonicalPath + " 不存在, 请先 mvn install");
    }

    @ResponseBody
    @RequestMapping({ "js/**", "css/**" })
    public void css(HttpServletRequest request, HttpServletResponse response) {
        String requestURI = request.getRequestURI();
        ResponseUtil.setContentTypeBySuffix(response, requestURI);

        File file = new File("../budo-warehouse-vue/dist" + requestURI);
        if (file.exists()) {
            IoUtil.write(IoUtil.fileInputStream(file), ResponseUtil.getOutputStream(response));
            return;
        }

        InputStream inputStream = ResourceUtil.classPathResourceInputStream(requestURI);
        if (null != inputStream) {
            IoUtil.write(inputStream, ResponseUtil.getOutputStream(response));
            return;
        }

        String canonicalPath = FileUtil.getCanonicalPath(file);
        ResponseUtil.writeToResponse(response, "#45 文件 " + canonicalPath + " 不存在");
    }
}